<template>
  <div class="login-container w-full h-full flex_fdc_aic_jcc">
    <!-- <img src="@/assets/images/login/logo.png" alt="" class="login_logo" /> -->
    <div class="login_title fs-24 mb32 nowrap">
      {{ $t("login.欢迎登录Mira商家管理系统") }}
    </div>
    <div class="login-box flex_fdc_aic_jcc">
      <div class="tabs flex pb26 mb6">
        <div
          class="tab_item"
          :class="{ active: activeTab === 'account' }"
          @click="handleTab('account')"
        >
          {{ $t("login.账号登录") }}
        </div>
        <div
          class="tab_item ml34"
          :class="{ active: activeTab === 'email' }"
          @click="handleTab('email')"
        >
          {{ $t("login.邮箱登录") }}
        </div>
      </div>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="formData"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <template v-if="activeTab === 'account'">
          <el-form-item prop="username" class="mt20">
            <el-input
              v-model="formData.username"
              class="login_input"
              style="width: 500px"
              :placeholder="$t('login.请输入用户名')"
            >
              <template #prefix>
                <img src="@/assets/images/login/user.png" alt="" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password" class="mt20">
            <el-input
              v-model="formData.password"
              type="password"
              class="login_input"
              style="width: 500px"
              :placeholder="$t('login.请输入密码')"
            >
              <template #prefix>
                <img src="@/assets/images/login/psw.png" alt="" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code" class="mt20">
            <div class="flex_aic">
              <el-input
                v-model="formData.code"
                class="login_input flex1"
                style="width: 500px"
                :placeholder="$t('login.请输入验证码')"
              >
                <template #prefix>
                  <img src="@/assets/images/login/code.png" alt="" />
                </template>
                <template #append>
                  <div @click="getAuthCode" class="login_code_box">
                    <img class="login_code" :src="codeImg" alt="" />
                  </div>
                </template>
              </el-input>
            </div>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item prop="email" class="mt20">
            <el-input
              v-model="formData.email"
              class="login_input"
              style="width: 500px"
              :placeholder="$t('login.请输入邮箱')"
            >
              <template #prefix>
                <img src="@/assets/images/login/user.png" alt="" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code" class="mt20">
            <div class="flex_aic">
              <el-input
                v-model="formData.code"
                class="login_input flex1"
                style="width: 500px"
                :placeholder="$t('login.请输入验证码')"
              >
                <template #prefix>
                  <img src="@/assets/images/login/code.png" alt="" />
                </template>
                <template #append>
                  <img class="login_code" :src="codeImg" alt="" />
                </template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="emailCode" class="mt20">
            <div class="flex_aic">
              <el-input
                v-model="formData.emailCode"
                class="login_input flex1"
                style="width: 500px"
                :placeholder="$t('login.请输入邮箱验证码')"
              >
                <template #prefix>
                  <img src="@/assets/images/login/code.png" alt="" />
                </template>
                <template #append>
                  <el-button
                    :disabled="countdown > 0"
                    @click="handleSendCode"
                    class="flex_shrink-0"
                    style="width: 180px"
                    :loading="sendCodeLoading"
                  >
                    {{
                      countdown > 0
                        ? `${countdown}s`
                        : $t("login.获取验证码")
                    }}
                  </el-button>
                </template>
              </el-input>
            </div>
          </el-form-item>
        </template>
        <el-button
          type="primary"
          class="login_btn"
          style="width: 500px; height: 40px"
          @click="handleLogin"
          ><span class="fs-20 font-bold">{{
            $t("login.立即登录")
          }}</span></el-button
        >
        <div class="flex_aic_jcsb mt10">
          <div
            v-if="activeTab === 'account'"
            class="fs-13 cursor-pointer"
            @click="showForgetPsw = true"
          >
            {{ $t("login.忘记密码") }}
          </div>
          <div v-else></div>
          <div class="fs-13">
            {{ $t("login.没有账号")
            }}<span
              class="color-primary cursor-pointer"
              @click="showRegister = true"
              >{{ $t("login.立即注册") }}</span
            >
          </div>
        </div>
      </el-form>
    </div>
    <forgetPsw v-model:show="showForgetPsw" />
    <register v-model:show="showRegister" @success="handleRegisterSuccess" />
    <entryDia v-model:show="showEntryDia" :status="entryStatus" />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import forgetPsw from "./forgetPsw.vue";
import register from "./register.vue";
import { useI18n } from "vue-i18n";
import entryDia from "./entryDia.vue";
import Api from "@/config/api/api";
import Tools from "@/utils/tools";
import { menuList_payment } from "@/components/layout/menu";

const { t, locale } = useI18n();
const router = useRouter();
const ruleFormRef = ref();
const formData = ref({
  username: "",
  password: "",
  code: "",
  smsCode: "",
  email: "",
  emailCode: ""
});
const activeTab = ref("account");
const countdown = ref(0);
const codeImg = ref("");
const uuid = ref("");
const rules = ref({
  username: [
    {
      required: true,
      message:
        activeTab.value === "account"
          ? t("login.请输入用户名")
          : t("login.请输入手机号"),
      trigger: "blur",
    },
    {
      validator: (rule, value, callback) => {
        if (activeTab.value === "email") {
          if (!value) {
            callback(new Error(t("login.请输入邮箱")));
          } else if (
            !/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)
          ) {
            callback(new Error(t("login.请输入正确的邮箱地址")));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: t("login.请输入密码"), trigger: "blur" },
  ],
  email: [
    { required: true, message: t("login.请输入邮箱"), trigger: "blur" },
  ],
  code: [{ required: true, message: t("login.请输入验证码"), trigger: "blur" }],
  smsCode: [
    { required: true, message: t("login.请输入短信验证码"), trigger: "blur" },
  ],
  emailCode:  [
    { required: true, message: t("login.请输入邮箱验证码"), trigger: "blur" },
  ],
});
const showRegister = ref(false);
const showForgetPsw = ref(false);
const showEntryDia = ref(false);
const entryStatus = ref(0);
const sendCodeLoading = ref(false);

const handleLogin = () => {
  Storage.set("isEntry", 0, true);

  ruleFormRef.value.validate((valid) => {
    if (valid) {
      let params = {};
      if (activeTab.value === "account") {
        params = {
          username: formData.value.username,
          password: Tools.rsaEncrypt(formData.value.password),
          code: formData.value.code,
          uuid: uuid.value,
        };
      } else {
        params = {
          email: formData.value.email,
          emailCode: formData.value.emailCode,
          code: formData.value.code,
          uuid: uuid.value,
        };
      }
      Api.login(params).then(async (res) => {
        if (res?.data?.user?.loginType == 1) {
          ElMessage.error(t("login.当前账号为平台账号，请使用商户账号登录"));
          return;
        }
        Storage.set("token", res?.data?.token, true);
        Storage.set("user", res?.data?.user, true);
        Storage.set("roles", res.data?.user?.roles || [], true);

        if (res?.status == 200) {
          const menuRes = await Api.getBuildMenu();
          Storage.set("menus", menuRes.data || [], true);
          router.push(getFirstMenu(menuRes.data));
        }else if(res?.status == 20002){
          // 已过期未缴费
          const menu = menuList_payment;
          Storage.set("menus", menu, true);
          router.push(getFirstMenu(menu));
        } else {
          getAuthCode();
          if (res?.status == 20003 || res?.status == 20004 || res?.status == 20001) {
            showEntryDia.value = true;
          }
          entryStatus.value = res?.status;
        }
      });
    } else {
      console.log("error submit!!");
    }
  });
};

const handleTab = (type) => {
  activeTab.value = type;
  formData.value = {
    username: "",
    password: "",
    code: "",
    smsCode: "",
  };
  ruleFormRef.value?.clearValidate();
};

const handleSendCode = async () => {
  try {
    const ref = await ruleFormRef.value.validateField(["email", "code"]);
    console.log("ref===", ref);
    const params = {
      email: formData.value.email,
    };
    sendCodeLoading.value = true;
    const res = await Api.loginEmailCode(params);
    if (res.status == 200) {
      countdown.value = 60;
      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);

      ElMessage.success(t("login.验证码发送成功"));
    }
    sendCodeLoading.value = false;
  } catch (error) {
    sendCodeLoading.value = false;
    ElMessage.error(error.message || t("login.验证码发送失败"));
  }
};

const getAuthCode = async () => {
  const res = await Api.authCode({});
  codeImg.value = res?.data?.img || "";
  uuid.value = res?.data?.uuid || "";
};

const getFirstMenu = (menu) => {
  const f = (arr) => {
    if (arr?.[0]?.path) return arr?.[0]?.path;
    if (arr?.[0]?.children?.length) {
      return f(arr?.[0]?.children);
    }
  };
  return f(menu) || "";
};

onMounted(() => {
  getAuthCode();
});
</script>

<style scoped lang="scss">
.login-container {
  background-image: url("@/assets/images/login/sld_login_bg.png");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;

  .login_logo {
    width: 144px;
    height: 48px;
    margin-bottom: 28px;
  }

  .login_title {
    color: #fff;
    font-family: Source Han Sans CN;
    font-weight: 500;
  }

  .tabs {
    .tab_item {
      width: 120px;
      text-align: center;
      font-size: 20px;
      line-height: 21px;
      cursor: pointer;
      position: relative;
      &.active {
        color: var(--primary-color);
        font-weight: 700;
        &::after {
          content: "";
          display: block;
          width: 72%;
          height: 3px;
          background-color: var(--primary-color);
          position: absolute;
          bottom: -20px;
          left: 50%;
          transform: translateX(-50%);
        }
      }
    }
  }
  .login-box {
    width: 600px;
    height: 420px;
    background-color: #fff;
    border-radius: 10px;

    :deep(.login_input) {
      height: 40px;
      border-radius: 2px;

      .el-input-group__append {
        padding: 0;
      }
    }
    .login_code {
      height: 40px;
      width: 96px;
    }
  }

  .login_phone_prefix {
    :deep(.el-select__wrapper) {
      border: none;
      box-shadow: none;
    }
  }
}
</style>
